Page({
  data: {
    loginUserInfo: {},
    score: 0  
  },

  logout() {
    const app = getApp();
    app.globalData.loginUserInfo = null;
    app.globalData.userId = null;
    wx.removeStorageSync('userId');
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  getUserScore() {
    const app = getApp();
    const username = app.globalData.loginUserInfo?.username;
    if (!username) {
      wx.showToast({ title: '获取用户信息失败', icon: 'none' });
      return;
    }

    wx.request({
      url: 'http://localhost:8080/score/page',
      method: 'GET',
      data: {
        'user.username': username,
        page: 1,
        size: 10
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 关键修正：score在list数组的第一个元素中
          const scoreList = res.data.data?.list || [];
          if (scoreList.length > 0) {
            this.setData({
              score: scoreList[0].score  // 正确路径：list[0].score
            });
          } else {
            this.setData({ score: 0 });
            wx.showToast({ title: '暂无积分记录', icon: 'none' });
          }
        } else {
          this.setData({ score: 0 });
          wx.showToast({ title: res.data.message || '获取积分失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('积分请求失败:', err);
        wx.showToast({ title: '网络错误，无法获取积分', icon: 'none' });
      }
    });
  },

  onLoad(options) {},

  onShow() {
    const app = getApp();
    if (!app.globalData.loginUserInfo) {
      wx.redirectTo({
        url: '/pages/login/login?url=/pages/mine/mine'
      });
    } else {
      this.setData({
        loginUserInfo: app.globalData.loginUserInfo
      });
      this.getUserScore();  // 页面显示时获取积分
    }
  },

  onReady() {},
  onHide() {},
  onUnload() {},

  onPullDownRefresh() {
    if (getApp().globalData.loginUserInfo) {
      this.getUserScore();
      wx.stopPullDownRefresh();
    }
  },

  onReachBottom() {},

  onShareAppMessage() {

  }
});